<script setup lang="ts">

import {message} from "ant-design-vue";
import SYCMCustomModalHeaderNotice from "~/components/SYCMCustomModalHeaderNotice.vue";
import BaseApp from "~/contentScripts/views/sycm/baseApp.vue";
import Shop_popular_artifact
  from "~/contentScripts/views/sycm/market_monitor/popular_artifact/shop_popular_artifact.vue";
import User from "~/contentScripts/views/tao/list/components/user.vue";
import {getCurrentInstance} from "vue";
// 爆款神器
import {isLogin} from "~/logic";
import SYCM from "~/utils/ali/sycm";
import McMqMarketRankInterception from "~/utils/interception/sycm/mcMqMarketRankInterception";
import RequestInterception from "~/utils/RequestInterception";

const {proxy} = getCurrentInstance();

const $req: RequestInterception = proxy.$req;
const loginVisible = ref(false);
const loading = ref(false);
const source = ref<any[]>([]);
let timer: any = null;
const visible = ref(false);
const title = ref('店铺');
const data = ref<{ 店铺: any | null, 商品: any | null, 品牌: any | null }>({
  店铺: {
    trade: null,
    flow: null,
  },
  商品: {
    trade: null,
    flow: null,
  },
  品牌: {
    trade: null,
    flow: null,
  },
});
const currData = ref<any>();
const __option = getCurrentInstance()?.appContext.provides.option;
const handle = async () => {
  if (isLogin({
    emit: () => {
      loginVisible.value = true;
    }
  }, __option)) {
    loading.value = true;
    let type = getType();
    if (data.value[type]['trade'] == null) {
      document.querySelector("[id^=__qiankun_microapp_wrapper_] .sycm-mc-mq-market-rank-container>div:nth-child(2) .oui-card-header-item span.oui-tab-switch-item:nth-child(1)").click();
    } else {
      document.querySelector("[id^=__qiankun_microapp_wrapper_] .sycm-mc-mq-market-rank-container>div:nth-child(2) .oui-card-header-item span.oui-tab-switch-item:nth-child(2)").click();
    }
    await loadData(type);

    if (!determineData(type)) {
      message.error('数据加载失败，请重试');
    } else {
      currData.value = {...data.value[type]};
      visible.value = true;
    }
    loading.value = false;
  }
}
const determineData = (type) => {
  if (data.value[type]['trade'] == null) {
    return false;
  }
  if (data.value[type]['flow'] == null) {
    return false;
  }
  return true;
}
const loadData = (type: string, tryNumber = 0) => {
  return new Promise((resolve) => {
    if (!determineData(type)) {
      setTimeout(() => {
        if (tryNumber > 10) {
          resolve(null);
        } else {
          loadData(type, tryNumber + 1).then(resolve);
        }
      }, 100);
    } else {
      resolve(data.value[type]);
    }
  });
}
const getType = () => {
  let type = document.querySelector("[id^=__qiankun_microapp_wrapper_] .ebase-FaCommonFilter-module__root .oui-tab-switch .oui-tab-switch-item.oui-tab-switch-item-active")?.innerHTML;
  // 移除空格
  type = type?.replace(/\s+/g, "");
  title.value = type;
  return type;
}
onMounted(() => {
  timer = setInterval(async () => {
    let type = getType();
    if (type) {
      // 高交易
      let dom = document.querySelector("[id^=__qiankun_microapp_wrapper_] .sycm-mc-mq-market-rank-container>div:nth-child(2) .oui-card-header-item span.oui-tab-switch-item:nth-child(1)");
      if (dom) {
        if (dom.className.includes('oui-tab-switch-item-active')) {
          let f = 'shop';
          switch (type) {
            case '店铺':
              f = 'shop-sale';
              break;
            case '商品':
              f = 'item';
              break;
            case '品牌':
              f = 'brand';
              break;
            default:
              f = 'shop';
          }
          let _data = await SYCM.getInternalFiberData('[id^=sycm-mc-mq-' + f + '] > div.oui-card-content', 'memoizedProps.children._owner.memoizedProps');
          if (_data && _data.tableData.data.length != 0) {
            if (data.value[type]['trade'] === null || JSON.stringify(data.value[type]['trade']) != JSON.stringify(_data.tableData)) {
              data.value[type]['trade'] = _data.tableData;
            }
          }
        }
      }
      // 流量
      let flowDom = document.querySelector("[id^=__qiankun_microapp_wrapper_] .sycm-mc-mq-market-rank-container>div:nth-child(2) .oui-card-header-item span.oui-tab-switch-item:nth-child(2)");
      if (flowDom) {
        if (flowDom.className.includes('oui-tab-switch-item-active')) {
          let f = 'shop';
          switch (type) {
            case '店铺':
              f = 'shop-search';
              break;
            case '商品':
              f = 'item';
              break;
            case '品牌':
              f = 'brand';
              break;
            default:
              f = 'shop';
          }
          let _data = await SYCM.getInternalFiberData('[id^=sycm-mc-mq-' + f + '] > div.oui-card-content', 'memoizedProps.children._owner.memoizedProps');
          if (_data && _data.tableData.data.length != 0) {
            if (data.value[type]['flow'] === null || JSON.stringify(data.value[type]['flow']) != JSON.stringify(_data.tableData)) {
              data.value[type]['flow'] = _data.tableData;
            }
          }
        }
      }
    }
  }, 300);
});
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<template>
  <base-app>
    <a-button-group>
      <user :style="{marginRight:0}"/>
      <a-button :loading="loading" size="small" @click="handle">爆款神器</a-button>
    </a-button-group>
    <custom-modal v-model:visible="visible" style="top: 20px;" width="95%" :title="`市场排行-${title}-爆款神器`">
      <template #headerRight>
        <SYCMCustomModalHeaderNotice/>
      </template>
      <shop_popular_artifact :data="currData" :title="title"/>
    </custom-modal>
    <user-login-modal :login-visible="loginVisible" @close="loginVisible=false"/>
  </base-app>
</template>

<style scoped>

</style>
